using Microsoft.EntityFrameworkCore;
using System;
using System.Linq;

namespace MovieDBReverseEngineering
{
    /// <summary>
    /// 演示应用程序
    /// 展示如何使用反向工程生成的数据库上下文和实体类
    /// </summary>
    class DemoApp
    {
        static void Main(string[] args)
        {
            Console.WriteLine("电影数据库反向工程演示应用");
            Console.WriteLine("==========================\n");

            try
            {
                // 选择数据库类型
                Console.WriteLine("请选择数据库类型：");
                Console.WriteLine("1. MySQL");
                Console.WriteLine("2. SQL Server");
                Console.Write("请选择: ");
                string dbType = Console.ReadLine();

                DbContextOptions<MovieDBContext> options;

                if (dbType == "1")
                {
                    // MySQL连接配置
                    Console.Write("请输入MySQL服务器地址 (默认localhost): ");
                    string server = Console.ReadLine();
                    if (string.IsNullOrWhiteSpace(server)) server = "localhost";

                    Console.Write("请输入端口号 (默认3306): ");
                    string portStr = Console.ReadLine();
                    int port = 3306;
                    if (!string.IsNullOrWhiteSpace(portStr) && int.TryParse(portStr, out int p))
                    {
                        port = p;
                    }

                    Console.Write("请输入用户名 (默认root): ");
                    string user = Console.ReadLine();
                    if (string.IsNullOrWhiteSpace(user)) user = "root";

                    Console.Write("请输入密码: ");
                    string password = ReadPassword();

                    // 创建MySQL连接选项
                    var optionsBuilder = new DbContextOptionsBuilder<MovieDBContext>();
                    optionsBuilder.UseMySQL($"server={server};port={port};database=MovieDB;user={user};password={password};");
                    options = optionsBuilder.Options;
                }
                else
                {
                    // SQL Server连接配置
                    Console.Write("请输入SQL Server服务器地址 (默认localhost): ");
                    string server = Console.ReadLine();
                    if (string.IsNullOrWhiteSpace(server)) server = "localhost";

                    Console.Write("是否使用Windows身份验证 (Y/N，默认Y): ");
                    string auth = Console.ReadLine();
                    bool useWindowsAuth = string.IsNullOrWhiteSpace(auth) || auth.ToUpper() == "Y";

                    string user = "", pwd = "";
                    if (!useWindowsAuth)
                    {
                        Console.Write("请输入用户名: ");
                        user = Console.ReadLine();

                        Console.Write("请输入密码: ");
                        pwd = ReadPassword();
                    }

                    // 创建SQL Server连接选项
                    var optionsBuilder = new DbContextOptionsBuilder<MovieDBContext>();
                    if (useWindowsAuth)
                    {
                        optionsBuilder.UseSqlServer($"Server={server};Database=MovieDB;Trusted_Connection=True;");
                    }
                    else
                    {
                        optionsBuilder.UseSqlServer($"Server={server};Database=MovieDB;User Id={user};Password={pwd};");
                    }
                    options = optionsBuilder.Options;
                }

                // 使用数据库上下文
                using (var context = new MovieDBContext(options))
                {
                    // 测试连接
                    context.Database.EnsureCreated();
                    Console.WriteLine("\n数据库连接成功！\n");

                    // 显示主菜单
                    ShowMainMenu(context);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"错误: {ex.Message}");
                if (ex.InnerException != null)
                {
                    Console.WriteLine($"内部错误: {ex.InnerException.Message}");
                }
            }

            Console.WriteLine("\n按任意键退出...");
            Console.ReadKey();
        }

        /// <summary>
        /// 显示主菜单
        /// </summary>
        private static void ShowMainMenu(MovieDBContext context)
        {
            bool exit = false;

            while (!exit)
            {
                Console.WriteLine("========= 演示菜单 ========");
                Console.WriteLine("1. 查看所有艺人");
                Console.WriteLine("2. 查看所有电影");
                Console.WriteLine("3. 查询电影演员");
                Console.WriteLine("4. 查询艺人作品");
                Console.WriteLine(0 + ". 退出");
                Console.Write("请选择: ");

                string choice = Console.ReadLine();
                Console.WriteLine();

                switch (choice)
                {
                    case "1":
                        ViewAllArtists(context);
                        break;
                    case "2":
                        ViewAllMovies(context);
                        break;
                    case "3":
                        QueryMovieArtists(context);
                        break;
                    case "4":
                        QueryArtistMovies(context);
                        break;
                    case "0":
                        exit = true;
                        break;
                    default:
                        Console.WriteLine("无效的选择\n");
                        break;
                }
            }
        }

        /// <summary>
        /// 查看所有艺人
        /// </summary>
        private static void ViewAllArtists(MovieDBContext context)
        {
            var artists = context.Artists.ToList();
            
            if (artists.Count == 0)
            {
                Console.WriteLine("暂无艺人信息\n");
                return;
            }

            Console.WriteLine("========= 艺人列表 ========");
            foreach (var artist in artists)
            {
                Console.WriteLine($"ID: {artist.Id}, 姓名: {artist.Name}");
                Console.WriteLine($"生日: {artist.Birthday?.ToString("yyyy-MM-dd") ?? "未知"}");
                Console.WriteLine($"性别: {artist.Sex ?? 'U'}");
                Console.WriteLine("--------------------------");
            }
            Console.WriteLine();
        }

        /// <summary>
        /// 查看所有电影
        /// </summary>
        private static void ViewAllMovies(MovieDBContext context)
        {
            var movies = context.Movies.ToList();
            
            if (movies.Count == 0)
            {
                Console.WriteLine("暂无电影信息\n");
                return;
            }

            Console.WriteLine("========= 电影列表 ========");
            foreach (var movie in movies)
            {
                Console.WriteLine($"ID: {movie.Id}, 片名: {movie.Name}");
                Console.WriteLine($"上映日期: {movie.Releasedate?.ToString("yyyy-MM-dd") ?? "未知"}");
                Console.WriteLine($"时长: {movie.Duration}分钟");
                Console.WriteLine("--------------------------");
            }
            Console.WriteLine();
        }

        /// <summary>
        /// 查询电影演员
        /// </summary>
        private static void QueryMovieArtists(MovieDBContext context)
        {
            Console.Write("请输入电影ID: ");
            if (int.TryParse(Console.ReadLine(), out int movieId))
            {
                var movie = context.Movies.Find(movieId);
                if (movie == null)
                {
                    Console.WriteLine("未找到该电影\n");
                    return;
                }

                Console.WriteLine($"电影 '{movie.Name}' 的演员列表：");
                
                var actors = context.Participations
                    .Where(p => p.Movieid == movieId)
                    .Include(p => p.Artist)
                    .ToList();

                if (actors.Count == 0)
                {
                    Console.WriteLine("暂无演员信息\n");
                    return;
                }

                foreach (var participation in actors)
                {
                    Console.WriteLine($"- {participation.Artist.Name} 饰演 {participation.Rolename ?? "未知角色"}");
                }
                Console.WriteLine();
            }
            else
            {
                Console.WriteLine("无效的电影ID\n");
            }
        }

        /// <summary>
        /// 查询艺人作品
        /// </summary>
        private static void QueryArtistMovies(MovieDBContext context)
        {
            Console.Write("请输入艺人ID: ");
            if (int.TryParse(Console.ReadLine(), out int artistId))
            {
                var artist = context.Artists.Find(artistId);
                if (artist == null)
                {
                    Console.WriteLine("未找到该艺人\n");
                    return;
                }

                Console.WriteLine($"艺人 '{artist.Name}' 的作品列表：");
                
                var movies = context.Participations
                    .Where(p => p.Artistid == artistId)
                    .Include(p => p.Movie)
                    .ToList();

                if (movies.Count == 0)
                {
                    Console.WriteLine("暂无作品信息\n");
                    return;
                }

                foreach (var participation in movies)
                {
                    Console.WriteLine($"- {participation.Movie.Name} ({participation.Rolename ?? "未知角色"})");
                }
                Console.WriteLine();
            }
            else
            {
                Console.WriteLine("无效的艺人ID\n");
            }
        }

        /// <summary>
        /// 读取密码（隐藏输入）
        /// </summary>
        private static string ReadPassword()
        {
            string password = "";
            ConsoleKeyInfo key;

            do
            {
                key = Console.ReadKey(true);
                
                if (key.Key != ConsoleKey.Backspace && key.Key != ConsoleKey.Enter)
                {
                    password += key.KeyChar;
                    Console.Write("*");
                }
                else if (key.Key == ConsoleKey.Backspace && password.Length > 0)
                {
                    password = password.Substring(0, password.Length - 1);
                    Console.Write("\b \b");
                }
            }
            while (key.Key != ConsoleKey.Enter);

            Console.WriteLine();
            return password;
        }
    }
}